package com.ruoyi.service.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.archive.domain.ArchiveCar;
import com.ruoyi.archive.domain.ArchiveRoom;
import com.ruoyi.archive.mapper.ArchiveCarMapper;
import com.ruoyi.archive.mapper.ArchiveRoomMapper;
import com.ruoyi.common.VelocityUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.service.domain.ServiceFitment;
import com.ruoyi.service.domain.ServiceTenancy;
import com.ruoyi.service.mapper.ServiceFitmentMapper;
import com.ruoyi.service.mapper.ServiceTenancyMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.service.mapper.ServiceChargeMapper;
import com.ruoyi.service.domain.ServiceCharge;
import com.ruoyi.service.service.IServiceChargeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 收费记录Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-04-21
 */
@Service
public class ServiceChargeServiceImpl implements IServiceChargeService 
{
    private static final Logger log = LoggerFactory.getLogger(ServiceChargeServiceImpl.class);

    @Autowired
    private ServiceChargeMapper serviceChargeMapper;
    @Autowired
    private ArchiveRoomMapper archiveRoomMapper;
    @Autowired
    private ArchiveCarMapper archiveCarMapper;
    @Autowired
    private ServiceFitmentMapper serviceFitmentMapper;
    @Autowired
    private ServiceTenancyMapper serviceTenancyMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询收费记录
     * 
     * @param id 收费记录主键
     * @return 收费记录
     */
    @Override
    public ServiceCharge selectServiceChargeById(Long id)
    {
        return serviceChargeMapper.selectServiceChargeById(id);
    }

    /**
     * 查询收费记录列表
     * 
     * @param serviceCharge 收费记录
     * @return 收费记录
     */
    @Override
    public List<ServiceCharge> selectServiceChargeList(ServiceCharge serviceCharge)
    {
        return serviceChargeMapper.selectServiceChargeList(serviceCharge);
    }

    /**
     * 新增收费记录,同步更新房屋和车辆的缴费期限
     * 
     * @param serviceCharge 收费记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertServiceCharge(ServiceCharge serviceCharge)
    {
        if(serviceCharge.getFeeType().equalsIgnoreCase(ServiceCharge.TYPE_ROOM)){
            ArchiveRoom room = archiveRoomMapper.selectArchiveRoomById(serviceCharge.getRoomId());
            if(room == null){
                throw new ServiceException("房屋不存在");
            }
            if(room.getToDate() != null && serviceCharge.getStartDate().before(room.getToDate())){
                throw new ServiceException("新开始时间不能早于原缴费时间");
            }
            room.setToDate(serviceCharge.getEndDate());
            archiveRoomMapper.updateArchiveRoom(room);
        }else if(serviceCharge.getFeeType().equalsIgnoreCase(ServiceCharge.TYPE_CAR)){
            ArchiveCar car = archiveCarMapper.selectArchiveCarById(serviceCharge.getCarId());
            if(car == null){
                throw new ServiceException("车辆不存在");
            }
            if(car.getToDate() != null && serviceCharge.getStartDate().before(car.getToDate())){
                throw new ServiceException("新开始时间不能早于原缴费时间");
            }
            car.setToDate(serviceCharge.getEndDate());
            archiveCarMapper.updateArchiveCar(car);
            serviceCharge.setRoomId(car.getRoomId());
        }

        serviceCharge.setCreateTime(DateUtils.getNowDate());
        serviceCharge.genNum();
        return serviceChargeMapper.insertServiceCharge(serviceCharge);
    }

    /**
     * 修改收费记录
     * 
     * @param serviceCharge 收费记录
     * @return 结果
     */
    @Override
    @Transactional
    public int updateServiceCharge(ServiceCharge serviceCharge)
    {
        serviceCharge.setUpdateTime(DateUtils.getNowDate());
        if(serviceCharge.getFeeType().equalsIgnoreCase(ServiceCharge.TYPE_TENANCY)){
            ServiceTenancy serviceTenancy = serviceTenancyMapper.selectServiceTenancyByChargeId(serviceCharge.getId());
            if(serviceTenancy != null){
                serviceTenancy.setChargeStatus(serviceCharge.getStatus());
                serviceTenancyMapper.updateServiceTenancy(serviceTenancy);
            }
        }else if(serviceCharge.getFeeType().equalsIgnoreCase(ServiceCharge.TYPE_DEPOSIT)){
            ServiceTenancy serviceTenancy = serviceTenancyMapper.selectServiceTenancyByChargeId(serviceCharge.getId());
            if(serviceTenancy != null){
                serviceTenancy.setChargeStatus(serviceCharge.getStatus());
                serviceTenancyMapper.updateServiceTenancy(serviceTenancy);
            }

            ServiceFitment serviceFitment = serviceFitmentMapper.selectServiceFitmentByChargeId(serviceCharge.getId());
            if(serviceFitment != null){
                serviceFitment.setChargeStatus(serviceCharge.getStatus());
                serviceFitmentMapper.updateServiceFitment(serviceFitment);
            }
        }
        return serviceChargeMapper.updateServiceCharge(serviceCharge);
    }

    /**
     * 批量删除收费记录
     * 
     * @param ids 需要删除的收费记录主键
     * @return 结果
     */
    @Override
    public int deleteServiceChargeByIds(Long[] ids)
    {
        return serviceChargeMapper.deleteServiceChargeByIds(ids);
    }

    /**
     * 删除收费记录信息
     * 
     * @param id 收费记录主键
     * @return 结果
     */
    @Override
    public int deleteServiceChargeById(Long id)
    {
        return serviceChargeMapper.deleteServiceChargeById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<ServiceCharge> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ServiceCharge row : dataList)
        {
            try
            {

                BeanValidators.validateWithException(validator, row);
                insertServiceCharge(row);

                /*
                // 验证是否存在旧数据
                ServiceCharge old = serviceChargeMapper.selectServiceChargeByName(row.getName());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertServiceCharge(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateServiceCharge(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、数据 " + row.getName() + " 已存在");
                }
                */
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum;// + "、数据 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 打印收费记录
     *
     * @param id 收费记录主键
     * @return 收费记录
     */
    @Override
    public String printServiceChargeById(Long id){
        ServiceCharge serviceCharge = selectServiceChargeById(id);
        if(serviceCharge == null){
            throw new ServiceException("收费单不存在");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("num", serviceCharge.getNum());
        data.put("date", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, serviceCharge.getCreateTime()));
        data.put("item", DictUtils.getDictLabel("fee_type", serviceCharge.getFeeType()));
        data.put("should", serviceCharge.getFeeShould());
        data.put("real", serviceCharge.getFeeReal());
        data.put("room", serviceCharge.getBuildingName()+" - " + serviceCharge.getUnitNum() + " - " + serviceCharge.getRoomName());
        if(serviceCharge.getCarId() != null){
            data.put("car", "车牌: " + serviceCharge.getCarId());
        }else{
            data.put("car", "");
        }
        return VelocityUtil.render("charge", data);
    }
}
